﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Framework;
using SchemaMonitor;
using SchemaMonitor.json;

public partial class usercontrols_UCDataView : CUsercontrolWithTable
{
	public bool IsEdit { get { return CWeb.RequestStr("edit").Length > 0 || CWeb.RequestStr("btnSaveData").Length > 0; } }
	public int TypeId { get { return CWeb.RequestInt("typeId", CSession.TypeId); } }
	public string NodeId { get { return CWeb.RequestStr("nodeId"); } }
			



	private bool _savePending = false;
	private bool _clone = false;
	private bool _delete = false;
	private CUser _user = null;
	private SchemaMonitor.CNode _node = null;



	private List<string> GetTags(SchemaMonitor.CNode node)
	{

		var tags = new List<string>() { "id" };
		foreach (var j in node.Root.Fields)
			if (!tags.Contains(j.Tag.TagName))
				tags.Add(j.Tag.TagName);
		return tags;
	}

	private void Page_Init(object sender, EventArgs e)
	{
		dd.DataSource = CTagType.Cache.FB_Post.MetaTags;
		dd.DataBind();
		CDropdown.BlankItem(dd, "-- Metatags --");

		rbl.DataSource = CTagType.Cache.FB_PostRating.MetaTags;
		rbl.DataBind();
		CDropdown.BlankItem(rbl, "NULL");
	}

	public void ShowData(CUser user)
	{
		var guid = CNodeRoot.Str2Guid(NodeId);
		var node = user.All.GetById(guid);
		if (null == node)
		{
			Response.Redirect(CSitemap.Data(string.Empty, TypeId));
			return;
		}
		ShowData(node, user);
	}
	public void ShowData(SchemaMonitor.CNode node,   CUser user)
	{
		_user = user;
		_node = node;

		var r = node.Root;
		var f = r.Fields;
		

		tbl.Visible = true;
		btnClone.Visible = !IsEdit;
		btnDelete.Visible = true;

		var o2o = CNodeLabels_OneToOne.Cache.GetById(_node.NodeGuid, CTagType.Cache.FB_PostRating.TypeId);
		if (null != o2o)
			CDropdown.SetValue(rbl, o2o.LabelTagId);
		else
			rbl.SelectedIndex = 0;

		var tr = new TableRow();

		//Show Chapters
		var cc = CChapter.Cache.GetByNodeGuid(node.NodeGuid);
		if (cc.Count > 0)
		{
			tbl.Rows.Add(tr);

			var th = new TableHeaderCell();
			tr.Cells.Add(th);
			th.Text = CUtilities.NameAndCount("Chapter", cc.Count);

			var td = new TableCell();
			tr.Cells.Add(td);

			foreach (var i in cc)
			{
				if (td.Controls.Count > 0)
				{
					var lit = new Literal();
					td.Controls.Add(lit);
					lit.Text = "<br/>";
				}
				var lnk = new HyperLink();
				lnk.Text = i.FullName;
				lnk.NavigateUrl = CSitemap.ChapterEdit(i.ChapterId);
				td.Controls.Add(lnk);
			}
		}

		var removeTagId = CWeb.RequestInt("removeTagId");
		if (removeTagId > 0)
		{
			var lbl = CNodeLabel.Cache.GetById(_node.NodeGuid, removeTagId);
			if (null != lbl)
				lbl.Delete();
			Response.Redirect(CSitemap.DataView(node), true);
		}


		var p = new CSoftPost(r, user);
		if (p.Labels.Count > 0 || true)
		{
			tr = new TableRow();
			tbl.Rows.Add(tr);

			var th = new TableHeaderCell();
			tr.Cells.Add(th);
			th.Text = CUtilities.NameAndCount("Metatag", p.Labels);

			var td = new TableCell();
			tr.Cells.Add(td);

			foreach (var i in p.Labels)
			{
				if (td.Controls.Count > 0)
				{
					var lit = new Literal();
					td.Controls.Add(lit);
					lit.Text = ", ";//"<br/>";
				}
				var lnk = new HyperLink();
				lnk.Text = i.MetaTag.TagName;
				lnk.NavigateUrl = CSitemap.DataView(_node) + "&removeTagId=" + i.LabelTagId;
				td.Controls.Add(lnk);
			}
		}

		List<string> tags = r.Tags;
		foreach (var key in tags)
		{
			tr = new TableRow();
			tbl.Rows.Add(tr);

			Th(tr, key);
			if (!f.Has(key))
			{
				Td(tr, string.Empty);
				continue;
			}

			//Custom Row
			if (false && CNodeRoot.PHOTO_IDS == key)
			{
				var tdp = Td(tr, string.Empty);
				var div = new Panel();
				//div.CssClass = "bigtext";
				//div.Style.Add("height", "300px");
				tdp.Controls.Add(div);

				var ids = f[key].AsLongList;
				var ctr = UCPhotos(div);
				ctr.Columns = 1;
				ctr.Width = 600;
				//ctr.Display(ids);
				continue;
			}
			else if ("attachments" == key && p.Attachments_ != null)
			{
				var tdp = Td(tr, string.Empty);
				var div = new Panel();
				tdp.Controls.Add(div);

				var ctr = UCPhotos(div);
				ctr.Display(p.Attachments_);
				ctr.Columns = 1;
				ctr.Width = 600;
				continue;
			}

			if ("comments" == key)
			{
				SpecialCell_Comments(tr, r, p);
				continue;
			}
		
			//Generic row
			var s = f[key].AsString;
			var td = IsEdit ? Td_Edit(tr, s, key, f, _savePending) : Td(tr, s, true);

			//ID Row
			if ("id" == key)
				SpecialRow_Id(node, r, td);
		}


		//Actions
		if (_delete)
		{
			node.Delete();
			_user.All.Remove(node);
			Response.Redirect(CSitemap.Data(string.Empty, node.Type.TypeId));
		}
		if (_savePending)
		{
			var older = new SchemaMonitor.CNode(node.NodeGuid);
			var diff = new CDiffList(older.Root, node.Root);
			if (diff.Count > 0)
			{
				node.Save();
				var c = new CChange(node, diff);
				c.Save();
			}

			node.Save();
			Response.Redirect(CSitemap.Data(node.Root.Id, node.Type.TypeId));
		}
		if (_clone)
		{
			var rc = new CNodeRoot(node.NodeDataAuto, node.Type);
			if (rc.HasPhotoIds)
				rc.PhotoIds = null;
			rc.Guid = Guid.NewGuid();
			rc.Persist(_user);
			Response.Redirect(CSitemap.Data(rc.Id, node.Type.TypeId));
		}

	}
	protected void dd_SelectedIndexChanged(object sender, EventArgs e)
	{
		var dd = (DropDownList)sender;
		var tagId = CDropdown.GetInt(dd);
		var lbl = CNodeLabel.Cache.GetById(_node.NodeGuid, tagId);
		if (null == lbl)
		{
			lbl = new CNodeLabel();
			lbl.LabelNodeGuid = _node.NodeGuid;
			lbl.LabelTagId = tagId;
			lbl.Save();
		}
		Response.Redirect(Request.RawUrl);
	}

	private void SpecialCell_Comments(TableRow tr, CNodeRoot r, CSoftPost post)
	{

		var tdp = Td(tr, string.Empty);
		var div = new Panel();
		tdp.Controls.Add(div);

		var ctr = UCComments(div);
		ctr.Display(post.Comments);

		return;

		var td = new TableCell();
		tr.Controls.Add(td);

		var pnl = new Panel();
		pnl.CssClass = "comments";
		td.Controls.Add(pnl);

		var f = r.Fields["comments"].AsPointerList(_user.All);
		foreach (var i in f)
		{
			var c = new CSoftComment(i.Root, _user);

			var p = new Panel();
			pnl.Controls.Add(p);
			p.CssClass = "comment";

			var lblName = new Label();
			lblName.Text = c.Name;
			lblName.Font.Bold = true;
			lblName.ToolTip = CUtilities.Timespan(c.CreatedTime);
			p.Controls.Add(lblName);

			var lblComment = new Label();
			lblComment.Text = c.Message;
			p.Controls.Add(lblComment);

			if (c.LikeCount > 0)
			{
				var lblLikes = new Label();
				lblLikes.Text = CUtilities.CountSummary(c.LikeCount, "like");
				lblLikes.Font.Bold = true;
				p.Controls.Add(lblLikes);
			}
		}
	}
	private void SpecialRow_Id(SchemaMonitor.CNode node, CNodeRoot r, TableCell td)
	{
		var g = r.Guid;

		if (IsEdit)
		{
			btnSaveData.Visible = true;
			btnCancel.Visible = true;

			var txt1 = (TextBox)td.Controls[0];
			txt1.Text = r.Id1.ToString();
			txt1.Width = new Unit(150);
			txt1.ID = "txtId1";

			var txt2 = new TextBox();
			txt2.Width = new Unit(150);
			txt2.ID = "txtId2";
			td.Controls.Add(txt2);

			CTextbox.SetNumber(txt1, r.Id1);
			CTextbox.SetNumber(txt2, r.Id2);

			if (_savePending)
			{
				var id1 = CWeb.RequestLong("txtId1");
				var id2 = CWeb.RequestLong("txtId2");
				if (r.Id1 != id1 || r.Id2 != id2)
				{
					r.Id = long.MinValue == id2 ? id1.ToString() : string.Concat(id1, "_", id2);
					var n = r.Persist(_user);
					if (node.NodeGuid != n.NodeGuid)
					{
						node.Root = null;
						node.Delete();
						_user.All.Remove(node);
					}
				}
			}

		}
		else
		{

			var t = CType.Cache.GetById(TypeId);
			lnkBack.Text = "Back to " + t.TypeName + "s";
			lnkBack.NavigateUrl = CSitemap.Data(string.Empty, TypeId);


			var lit = new Literal();
			lit.Text = td.Text;
			td.Controls.Add(lit);

			var lnk = new HyperLink();
			lnk.Text = "Edit...";
			lnk.Font.Bold = true;
			lnk.Font.Size = new FontUnit(FontSize.Larger);
			lnk.NavigateUrl = CSitemap.Data(r.Id, TypeId, !IsEdit);
			lnk.Style.Add("float", "right");
			lnk.Style.Add("margin-left", "20px");
			td.Controls.Add(lnk);
		}
	}




	protected void btnSaveData_Click(object sender, EventArgs e)
	{
		_savePending = true;
	}

	protected void btnCancel_Click(object sender, EventArgs e)
	{
		Response.Redirect(CSitemap.Data(CSession.SearchData, TypeId));
	}

	protected void btnClone_Click(object sender, EventArgs e)
	{
		_clone = true;
	}

	protected void btnDelete_Click(object sender, EventArgs e)
	{
		_delete = true;
	}


	//Obsolete

	/*
	protected void btnFrom_Click(object sender, EventArgs e)
	{
		var fromId = txtFrom.Text;
		var id = txtSearch.Text;
		var from = _user.All.Search(fromId);
		var to = _user.All.Search(id);

		var f = from[0];
		var t = to[0];
		var ff = f.Root;
		var tt = t.Root;

		if (!ff.HasPhotoIds)
			return;

		var temp = ff.PhotoIds;
		ff.PhotoIds = null;

		if (tt.HasPhotoIds)
			tt.PhotoIds.AddRange(temp);
		else
			tt.PhotoIds = temp;
		t.Save();
		f.Save();
		Response.Redirect(Request.RawUrl);
	}

	protected void btnRelease_Click(object sender, EventArgs e)
	{
		var id = txtSearch.Text;
		var to = _user.All.Search(id);

		var t = to[0];
		t.Root.PhotoIds = null;
		t.Save();
		Response.Redirect(Request.RawUrl);

	}
	*/



	#region Private - Usercontrols
	private usercontrols_UCPhotos UCPhotos(Control target)
	{
		Control ctrl = Page.LoadControl("~/usercontrols/UCPhotos.ascx");
		target.Controls.Add(ctrl);
		return (usercontrols_UCPhotos)ctrl;
	}
	private usercontrols_UCComments UCComments(Control target)
	{
		Control ctrl = Page.LoadControl("~/usercontrols/UCComments.ascx");
		target.Controls.Add(ctrl);
		return (usercontrols_UCComments)ctrl;
	}

	#endregion



	protected void rbl_SelectedIndexChanged(object sender, EventArgs e)
	{
		var tt = CTagType.Cache.FB_PostRating;
		var lbl = CNodeLabels_OneToOne.Cache.GetById(_node.NodeGuid, tt.TypeId);
		if (null == lbl)
		{
			lbl = new CNodeLabels_OneToOne();
			lbl.LabelTypeId = tt.TypeId;
			lbl.LabelNodeGuid = _node.NodeGuid;
		}
		lbl.LabelTagId = CDropdown.GetInt(rbl);
		if (lbl.LabelTagId < 0)
			lbl.Delete();
		else
			lbl.Save();
		Response.Redirect(CSitemap.DataView(_node), true);
	}
}